package com.challenge.Action;

import com.alibaba.fastjson.JSONObject;
import com.challenge.Constants.IConstants;
import com.challenge.Kitchen.Kitchen;
import com.challenge.Order.Order;
import com.challenge.util.PossionMath;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DriverDispatcherProcess {

    int count = 1;
    /**
     * Drivers should be dispatched
     * using a Poisson Distribution with an average of 3 drivers per second until no orders are left on
     * the shelves
     * @param kitchen
     */
    public void driverDispatcher(Kitchen kitchen){
        System.out.println("Drivers dispatched =====>");

        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if(kitchen.getSortShelf().store.size()>0){
                    int driverNumber = PossionMath.getPossionVariable(3); // Poisson number
                    ArrayList<Order> orders = new ArrayList<Order>();
                    System.out.println("this time Drivers Num [" + driverNumber +"]");
                    for(Order order:kitchen.getSortShelf().store){
                        if(order.getLeftLifeTime()<=0){ //Orders that have reached a value of zero are considered waste and should be removed from the shelves
                            orders.add(order);
                            System.out.println("order : " + JSONObject.toJSONString(order) + " waste");
                            continue;
                        }
                        order.setLeftLifeTime(order.getLeftLifeTime()-1);
                        if(driverNumber>0){
                            kitchen.getShelfContent().getContent().get(order.getShelfType()).getStore().remove(order);
                            orders.add(order);
                            System.out.println("get the order" + JSONObject.toJSONString(order));
                            driverNumber -- ;
                        }
                    }
                    for(Order order:orders){
                        kitchen.getSortShelf().store.remove(order);
                    }

                    System.out.println("num:" +count + " Delivery ; left orders [" + kitchen.getSortShelf().store.size() + "]  ");
                    count++;
                }else{
                    System.out.println("no orders are left on the shelves");
                    executorService.shutdown();
                }

            }
        }, 0, 1000, TimeUnit.MILLISECONDS);
    }

}
